const { formatTimeCommon, calculateAge, calculateConstellation } = require('../../utils/filter.js');
const qiniuUploader = require("../../utils/qiniuUploader");
const QQMapWX = require('../../utils/qqmap-wx-jssdk.min');
let qqmapsdk = null;
const heights = Array(...Array(81)).map((_, idx) => idx + 140);
const { HTTP } = require('../../utils/http');
const { api } = require('../../utils/api');
const { request } = new HTTP();
let selectPronvice = '';
let haveEdit = false;
const app = getApp()

Page({
  data: {
    active: 1,
    photos: [
      {src: '', index: 0},
      {src: '', index: 1},
      {src: '', index: 2},
      {src: '', index: 3},
      {src: '', index: 4},
      {src: '', index: 5}
    ],
    currentDate: new Date(1994, 1, 1).getTime(),
    minDate: new Date(1900, 1, 1).getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    heightcolumns: heights,
    cityList: [
      {
        values: [],
        className: 'column1'
      },
      {
        values: [],
        className: 'column2',
      }
    ],
    currentCity: {
      index: [0, 0],
      value: ['北京', '北京']
    },
    loading: false,
    hobby: {
      sex: '1',
      rangeValuesHeight: [150, 180],
      rangeValuesAge: [20, 40],
      position: ''
    },
    userInfo: {
      nickname: '',
      birthday: '',
      sex: '1',
      age: null,
      constellation: '',
      height: 160,
      province_id: '',
      province: '',
      city_id: '',
      city: '',
      school: '',
      company: '',
      profession: '',
      wishs: [],
      dailys: []
    }
  },
  onShow(){},
  onLoad() {
    qqmapsdk = new QQMapWX({
      key: '3HLBZ-DACKD-YRP4I-HZE6V-KVSPV-P6FGR'
    });
    this._getProvinces();
    this._getToken();
  },
  getLocation() {
    const self = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        const latitude = res.latitude;
        const longitude = res.longitude;
        qqmapsdk.reverseGeocoder({
          location: {
            longitude,
            latitude
          },
          success: function(res) {
            const position = res.result.address_component.city  + ' ' + res.result.address_component.district;
            self.setData({
              'hobby.position': position
            })
          }
        })
      }
    })
  },
  next() {
    if (this.data.active === 1) {
      if (!this.data.userInfo.nickname) {
        wx.showToast({ title: '昵称不能为空', icon: 'none', duration: 2000 });
        return;
      }
      if (!this.data.userInfo.school) {
        wx.showToast({ title: '学校不能为空', icon: 'none', duration: 2000 });
        return;
      }
    }
    if (this.data.active === 5) {
      this._cityConfirm();
    }
    if (this.data.active === 9) {
      const havePhoto = this.data.photos.find(item => item.src);
      if (!havePhoto) {
        wx.showToast({ title: '请至少上传一张照片', icon: 'none', duration: 2000 });
        return;
      };
      this._loopUplaodPhoto(this.data.photos);
      return;
    }
    this.setData({
      active: this.data.active + 1
    })
  },
  onRangeChange(e) {
    let { detail: {minValue, maxValue} } = e;
    this.setData({
      'hobby.rangeValuesHeight': [Math.round(minValue), Math.round(maxValue)]
    });
  },
  onRangeAgeChange(e) {
    let { detail: {minValue, maxValue} } = e;
    this.setData({
      'hobby.rangeValuesAge': [Math.round(minValue), Math.round(maxValue)]
    });
  },

  _loopUplaodPhoto(photos) {
    for(let i = 0; i < photos.length; i++) {
      photos[i].src && this.uplodQiniu(photos[i].src, photos[i].index);
      if (i === photos.length -1) {
        haveEdit 
        ? this._back
        : this._edit(this.data.userInfo, () => {
          this._back();
        });
      }
    }
  },
  _back() {
    const self = this;
    wx.showToast({ title: '编辑资料成功', icon: 'none', duration: 2000, success: function() {
      self._getUserInfo();
      wx.navigateBack({
        delta: 1
      });
    }});
  },

  async _edit(userInfo, cb, avatar) {
    userInfo.wish = userInfo.wishs.join('|~|~');
    userInfo.daily = userInfo.dailys.join('|~|~');
    if (avatar) userInfo.avatar = avatar;
    // 配爱好
    const marry_like = {
      sex: this.data.hobby.sex,
      position: this.data.hobby.position,
      minAge: this.data.hobby.rangeValuesAge[0],
      maxAge: this.data.hobby.rangeValuesAge[1],
      minHeight: this.data.hobby.rangeValuesHeight[0],
      maxHeight: this.data.hobby.rangeValuesHeight[1],
    };
    userInfo.marry_like = JSON.stringify(marry_like);
    const {returnCode = '', bean = {}} = await request({
      url: api.editUser,
      method: 'put',
      data: userInfo
    });
    if (returnCode === '0000') {
      haveEdit = true;
      cb && cb();
    }
  },
  
  nicknameInput(event) {
    const { detail: {value = ''} } = event;
    this.setData({
      'userInfo.nickname': value
    });
  },
  onSexChange(event) {
    this.setData({
      'userInfo.sex': event.detail,
    });
  },
  onSexClick(event) {
    const { name } = event.currentTarget.dataset;
    this.setData({
      'userInfo.sex': name,
    });
  },
  onHobbyChange(event) {
    this.setData({
      'hobby.sex': event.detail,
    });
  },
  onHobbyClick(event) {
    const { name } = event.currentTarget.dataset;
    console.log('🚀 ~ file: index.js ~ line 209 ~ onHobbyClick ~ name', name)
    this.setData({
      'hobby.sex': name,
    });
  },
  schoolInput(event) {
    const { detail: {value = ''} } = event;
    this.setData({
      'userInfo.school': value
    });
  },
  companyInput(event) {
    const { detail: {value = ''} } = event;
    this.setData({
      'userInfo.company': value
    });
  },
  professionInput(event) {
    const { detail: {value = ''} } = event;
    this.setData({
      'userInfo.profession': value
    });
  },
  // 生日选择
  onInput(event) {
    const { detail } = event;
    const age = calculateAge(detail);
    const constellation = calculateConstellation(detail);
    detail && this.setData({
      'userInfo.birthday': formatTimeCommon(detail),
      'userInfo.age': age,
      'userInfo.constellation': constellation
    });
  },
  dailyInput(event) {
    let { currentTarget: { dataset: { index } }, detail: { value } } = event;
    index = Number(index);
    if (this.data.userInfo.dailys[index]) {
      this.data.userInfo.dailys[index] = value;
      this.setData({
        'userInfo.dailys': this.data.userInfo.dailys
      });
    } else {
      this.data.userInfo.dailys.push(value);
      this.setData({
        'userInfo.dailys': this.data.userInfo.dailys
      });
    }
  },
  wishInput(event) {
    let { currentTarget: { dataset: { index } }, detail: { value } } = event;
    index = Number(index);
    
    if (this.data.userInfo.wishs[index] ) {
      this.data.userInfo.wishs[index] = value
      this.setData({
        'userInfo.wishs': this.data.userInfo.wishs
      });
    } else {
      this.data.userInfo.wishs.push(value);
      this.setData({
        'userInfo.wishs': this.data.userInfo.wishs
      });
    }
  },
  // 选择身高
  onHeightChange(event) {
    const { detail: { value } } = event;
    this.setData({
      'userInfo.height': value
    });
  },

  // 城市
  onCityChange(event) {
    const { picker, value, index } = event.detail;
    if (selectPronvice && value[0].code == selectPronvice) {
      return;
    }
    selectPronvice = value[0].code;
    this._getCitys(value[0].code, (citys) => {
      picker.setColumnValues(1, citys);
    });

  },
  _cityConfirm() {
    const value = this.selectComponent('#cityPicker').getValues();
    this.setData({
      'userInfo.province_id': value[0].code,
      'userInfo.province': value[0].name,
      'userInfo.city_id': value[1].code,
      'userInfo.city': value[1].name
    })
  },

  // 获取省份信息
  async _getProvinces() {
    const {returnCode = '', beans = []} = await request({
      url: api.getProvinces,
      method: 'get',
      data: {}
    });
    if (returnCode === '0000') {
      const key = `cityList[${0}].values`
      this.setData({
        [key]: beans
      });
      this._getCitys(this.data.userInfo.province_id || 101010000, () => {}, true);
    }
  },

  // 获取城市
  async _getCitys(provinceCode, cb, isFirst = false) {
    this.setData({ loading: true });
    const {returnCode = '', beans = []} = await request({
      url: api.getCitys,
      method: 'get',
      data: {provinceCode}
    });
    this.setData({ loading: false });
    if (returnCode === '0000') {
      const key = `cityList[${1}].values`
      this.setData({
        [key]: beans
      });
      cb && cb(beans);
    }
  },

  upload(event) {
    let { id } = event.currentTarget;
    id = Number(id);
    const self = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths
        self.data.photos[id].src = tempFilePaths[0];
        self.setData({
          photos: self.data.photos
        });
      }
    })
  },
  // 获取七牛上传token
  async _getToken() {
    const { returnCode = null, bean = {} } = await request({
      url: api.getQiniuToken,
      method: 'get',
      data: {}
    });
    if (returnCode === '0000') {
      this.setData({
        qiniuToken: bean.qiniuToken
      });
      this._initQiniu();
    }
  },

  // 初始化七牛配置
  _initQiniu() {
    const options = {
        region: 'ECN',
        uptoken: this.data.qiniuToken,
        uptokenURL: '',
        uptokenFunc: function () { },
        domain: 'https://paas.star1024.cn',
        shouldUseQiniuFileName: false
    };
    qiniuUploader.init(options);
  },

  // 上传七牛
  async uplodQiniu(filePath, index) {
    const self = this;
    qiniuUploader.upload(filePath, (res) => {
      const params = {
        image: res.imageURL,
        index
      };
      self._addUserImage(params, index);
    }, (error) => {
      wx.showToast({
        title: JSON.stringify(error),
        icon: 'none',
        duration: 2000
      });
      console.error('error: ' + JSON.stringify(error));
    },
    null,
    (progress) => {
      console.log('上传进度', progress.progress);
    }, cancelTask => {
      console.log('🚀 ~ file: index.js ~ line 65 ~ uplodQiniu ~ cancelTask', cancelTask);
    });
  },
  // 将七牛云链接存入数据库
  async _addUserImage(params, index) {
    const { returnCode = null, bean = {} } = await request({
      url: api.addUserImage,
      method: 'post',
      data: params
    });
    if (returnCode === '0000') {
      if (index === 0) {
        this._edit(this.data.userInfo, () => {}, params.image);
      }
    }
  },
  async _getUserInfo() {
    const {returnCode = '', bean = {}} = await request({
      url: api.getUser,
      method: 'get',
      data: {}
    });
    
    if (returnCode === '0000') {
      app.globalData.userInfo = bean.user;
    }
  }

})
